package org.apselex.adaptors;

/*
 * Copyright (c) 2008 Evan Williams
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.log4j.Logger;
import org.apselex.model.ModelElement;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.filesystem.IFileSystem;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Path;
import org.eclipse.images.providers.ImageProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Image;

import apselmodel.Activator;


public class ModelElementImageProvider implements ImageProvider {

	private ModelElement element = null;

	private static Logger logger = Logger.getLogger(ModelElementImageProvider.class);

	/**
	 * @param element
	 */
	public ModelElementImageProvider(ModelElement element) {
		logger.debug("meip constructor called");
		this.element = element;
	}

	@Override
	public void disposeImage(Image image) {
		// TODO Auto-generated method stub

	}

	@Override
	public Image getImage(Device target) {
		// TODO Auto-generated method stub

		logger.debug("in getImage");
		InputStream in = null;
		IFileSystem fs = EFS.getLocalFileSystem();

		try {
			Path p = new Path(this.element.getFilename());
			IFileStore store = fs.getStore(p);
			logger.debug("got store ..." + store);

			in = store.openInputStream(0, null);
			return new Image(target, in);
		} catch (SWTException e) {
			if (e.code != SWT.ERROR_UNSUPPORTED_FORMAT) {
				logger.debug("error :" + e);
			}
		} catch (Exception e) {
			logger.debug("exception :" + e);
		} finally {
			try {
				in.close();
			} catch (IOException e) {
			}
		}
		return null;

	}
}
